﻿using PhotoGallery.Data.Entity;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Xml.Linq;

namespace PhotoGallery.Data.Repository
{
    public class VideoRepository : BaseRepository
    {
        private List<Video> videos;
        private XDocument doc;
        string path;
        Album album;

        public VideoRepository(Album currentAlbum, string owner)
        {
            Owner = owner;
            album = currentAlbum;
            string albumFolder = getAlbumFolder(album);
            LoadData(album.ID, albumFolder);
        }

        public VideoRepository(int albumID, string owner, string albumFolder)
        {
            Owner = owner;
            LoadData(albumID, albumFolder);
        }

        public IEnumerable<Video> Get()
        {
            return videos;
        }

        public Video Get(int id)
        {
            return videos.FirstOrDefault(m => m.ID == id);
        }

        public Video GetFirst()
        {
            return videos.FirstOrDefault();
        }

        public IEnumerable<VideoAttachments> GetAttachments(int videoID)
        {
            var entity = new VideoAttachments();
            VideoAttachmentsRepository repo = new VideoAttachmentsRepository(album.ID, videoID, Owner);
            return repo.Get();
        }

        public void Create(Video video)
        {
            video.ID = GetMaxValue() + 1;
            video.UploadedOn = DateTime.UtcNow;
            
            videos.Add(video);
            doc.Root.Add(new XElement("video",
                              new XElement("id", video.ID),
                              new XElement("title", video.Title),
                              new XElement("filename", video.FileName),
                              new XElement("thumbnail", video.Thumbnail),
                              new XElement("description", video.Description),
                              new XElement("uploadedOn", ConvertDate(video.UploadedOn)),
                              new XElement("modifiedOn", null),
                              new XElement("deletedOn", null),
                              new XElement("shared", video.Shared),
                              new XElement("orderNumber", GetMaxOrderNumber() + 1),
                              new XElement("active", true)
                              ));

            doc.Save(path + Settings.VideoMetaDataXml);

        }

        public void Update(Video video)
        {
            video.ModifiedOn = DateTime.UtcNow;
            XElement node = doc.Root.Elements("video").Where(i => (int)i.Element("id") == video.ID).FirstOrDefault();

            node.SetElementValue("id", video.ID);
            node.SetElementValue("title", video.Title ?? "");
            node.SetElementValue("filename", video.FileName);
            node.SetElementValue("thumbnail", video.Thumbnail ?? "");
            node.SetElementValue("description", video.Description ?? "");
            node.SetElementValue("modifiedOn", ConvertDate(video.ModifiedOn));
            node.SetElementValue("shared", (int)video.Shared);
            
            doc.Save(path + Settings.VideoMetaDataXml);
        }

        public void Delete(Video video)
        {
            video.DeletedOn = DateTime.UtcNow;
            XElement node = doc.Root.Elements("video").Where(i => (int)i.Element("id") == video.ID).FirstOrDefault();

            node.SetElementValue("modifiedOn", ConvertDate(video.ModifiedOn) ?? ConvertDate(DateTime.UtcNow));
            node.SetElementValue("active", false);

            doc.Save(path + Settings.VideoMetaDataXml);
        }

        public void Erise(int id)
        {
            Video video = videos.FirstOrDefault(i => i.ID == id);

            doc.Root.Elements("video").Where(i => (int)i.Element("id") == id).Remove();
            doc.Save(path + Settings.VideoMetaDataXml);
        }

        #region privateMethods

        private int GetMaxValue()
        {
            int count = doc.Descendants("video").Count();
            if (count > 0)
            {
                var maxID = (from prod in doc.Descendants("video")
                             select
                             (
                                         int.Parse(prod.Element("id").Value)
                             )).Max();

                return maxID;
            }
            else
            {
                return 0;
            }
        }


        private int GetMaxOrderNumber()
        {
            int count = doc.Descendants("video").Count();
            if (count > 0)
            {
                var maxID = (from prod in doc.Descendants("video")
                             select
                             (
                                         int.Parse(prod.Element("orderNumber").Value)
                             )).Max();

                return maxID;
            }
            else
            {
                return 0;
            }
        }

        private void LoadData(int albumID, string albumFolder = "")
        {
            videos = new List<Video>();
            string albumUrl = "/Videos/";
            //if (String.IsNullOrEmpty(albumFolder))
            //{
            //    album = new AlbumRepository(Owner).Get(albumID);
            //    path = BasePath + Settings.UploadsFolder + Owner + "\\Videos\\" + getAlbumFolder(album);
            //    albumUrl += getAlbumUrl(album);
            //}
            //else
            //{
                path = BasePath + Settings.UploadsFolder + Owner + "\\Videos\\" + albumFolder + "\\";
                albumUrl += albumFolder + "/";
            //}

            doc = XDocument.Load(path + Settings.VideoMetaDataXml);
            var qry = from video in doc.Descendants("video")
                      select new Video(
                                         Convert.ToInt32(video.Element("id").Value),
                                         video.Element("title").Value,
                                         video.Element("filename").Value,
                                         video.Element("thumbnail").Value,
                                         video.Element("description").Value,
                                         ConvertDate(video.Element("uploadedOn").Value),
                                         ConvertDate(video.Element("modifiedOn").Value),
                                         ConvertDate(video.Element("deletedOn").Value),
                                         (SharedAlbum)Enum.Parse(typeof(SharedAlbum), video.Element("shared").Value),
                                         Convert.ToInt32(video.Element("orderNumber").Value),
                                         video.Element("active").Value == "false" ? false : true
                                       );
            videos.AddRange(qry.Where(x => x.Active == true).OrderByDescending(x => x.OrderNumber).ThenByDescending(x=>x.ID).ToList<Video>());
        }


        #endregion
    }
}